package com.mzba.easy.weibo.util;

import java.io.File;

import android.content.Context;

public class ImageFileCache {
    
    private File cacheDir;
    
    public ImageFileCache(Context context, String path){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), path);
        else
            cacheDir = context.getCacheDir();
        if (!cacheDir.exists())
            cacheDir.mkdirs();
    }
    
    public File getFile(String url){
        String filename = null;
		try {
//			filename = URLEncoder.encode(url, "UTF-8");
			filename = convertUrlToFileName(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
        File f = new File(cacheDir, filename);
        return f;
        
    }
    
    public void clear(){
		File[] files = cacheDir.listFiles();
		if (files == null)
			return;
		for (File f : files)
			f.delete();
    }
    
    private String convertUrlToFileName(String url) {
		String filename = url;
		String pre = filename.substring(0, filename.lastIndexOf("sinaimg.cn") + 11);
		filename = filename.replace(pre, "");
		filename = filename.replace("/", "_");
		String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
		if (suffix.equals("jpg")) {
			filename = filename.replace("jpg", "dat");
		} else if (suffix.equals("gif")) {
			filename = filename.replace("gif", "dat");
		} else if (suffix.equals("jpeg")) {
			filename = filename.replace("jpeg", "dat");
		} else if (suffix.equals("png")) {
			filename = filename.replace("png", "dat");
		} else {
			filename = filename + ".dat";
		}
		return filename;
	}

}